package com.linln.admin.meeting.service.impl;

import com.linln.admin.meeting.domain.OrderInfo;
import com.linln.admin.meeting.repository.OrderRepository;
import com.linln.admin.meeting.service.OrderService;
import com.linln.common.data.PageSort;
import com.linln.common.exception.BusinessException;
import com.linln.component.shiro.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author taofucheng
 * @date 2021/10/25
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;


    /**
     * 获取分页列表数据
     *
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<OrderInfo> getPageList(Example<OrderInfo> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return orderRepository.findAll(example, page);
    }

    /**
     * 根据ID查询数据
     *
     * @param id 主键ID
     */
    @Override
    public OrderInfo getById(Long id) {
        return orderRepository.findById(id).orElse(null);
    }

    /**
     * 保存数据
     *
     * @param orderInfo 实体对象
     */
    @Override
    public OrderInfo save(OrderInfo orderInfo) {
        return orderRepository.save(orderInfo);
    }

    @Override
    public List<OrderInfo> getRangeAllMeetings(String groupId, String start, String end) {
        groupId = StringUtils.trim(groupId);
        if (StringUtils.isBlank(groupId) || !StringUtils.isNumeric(groupId)) {
            return null;
        }
        try {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.CHINA);
            Date sTime = DateUtils.truncate(new Date(), Calendar.DATE);
            if (StringUtils.isNotBlank(start)) {
                start = start.substring(0, 19);
                sTime = format.parse(start);
            }

            Date eTime = DateUtils.addDays(sTime, 1);
            if (StringUtils.isNotBlank(end)) {
                end = end.substring(0, 19);
                eTime = format.parse(end);
            }
            return orderRepository.selectOrdersByRange(Long.parseLong(groupId), sTime, eTime);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Transactional
    @Override
    public OrderInfo takeRoom(Long roomId, Date startTime, Date endTime) {
        if (endTime.before(new Date())) {
            throw new BusinessException("你不能预订过去的时间，已经逝去的时间就让它逝去吧！");
        }
        //时间各缩进1s，方便正确判断
        Date start = DateUtils.addSeconds(startTime, 1);
        Date end = DateUtils.addSeconds(endTime, -1);
        if (orderRepository.existsByTimeRange(roomId, start, end) > 0) {
            throw new BusinessException("该会议室在选定的时间段已经有人预订过了，请重新刷新页面查看！");
        }
        OrderInfo order = new OrderInfo();
        order.setMeetingId(roomId);
        order.setUserId(ShiroUtil.getSubject().getId());//当前登录用户
        order.setSubject("预订会议");
        order.setPersons(1);
        order.setStartTime(startTime);
        order.setEndTime(endTime);
        orderRepository.save(order);
        return order;
    }

    @Transactional
    @Override
    public void deleteById(Long orderId) {
        if (orderId == null) {
            return;
        }
        orderRepository.deleteById(orderId);
    }

    @Override
    @Transactional
    public void cancel(Long orderId) {
        OrderInfo orderInfo = getById(orderId);
        if (orderInfo == null) {
            throw new BusinessException("预约信息不存在！");
        }
        if (orderInfo.getEndTime().before(new Date())) {
            throw new BusinessException("结束的会议不能取消！");
        }
        deleteById(orderId);
    }

}
